package com.lanou.fooddemo.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.TextView;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.lanou.fooddemo.R;
import com.lanou.fooddemo.adapter.MainTabFragmentAdapter;
import com.lanou.fooddemo.external.sliding_menu.SlidingMenu;
import com.lanou.fooddemo.fragment.RecommendFragment;
import com.lanou.fooddemo.fragment.SameCityFragment;
import com.lanou.fooddemo.fragment.SelectedFragment;
import com.lanou.fooddemo.fragment.TopicsFragment;
import com.lanou.fooddemo.listener.MainTabMenuItemOnClickListener;
import com.lanou.fooddemo.theme.FoodTheme;
import com.lanou.fooddemo.util.BaiDuMapUtil;
import com.lanou.fooddemo.util.CommonUtil;
import com.lanou.fooddemo.view.FoodToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MainTabActivity extends FragmentActivity {
    private final String LOG_TAG = "MainTabActivity";

    /**
     * TabHost同城Tab的Tag
     */
    private final String SAME_CITY = "SameCity";
    private final String TOPIC = "Topic";
    private final int SAME_CITY_POSITION = 0;
    private final String SELECTED = "Selected";
    private final String RECOMMEND = "Recommend";
    private final String SAME_CITY_TITLE = "同 城";
    private final String TOPIC_TITLE = "话 题";
    private final String RECOMMEND_TITLE = "推 荐";
    private final String SELECTED_TITLE = "精 选";

    private SlidingMenu mLeftMenu ;
    /**
     * 内容ViewPager
     */
    private ViewPager mainTabViewPager;
    private TextView titleTextView;
    private MainTabFragmentAdapter adapter;
    /**
     * 底部TabHost
     */
    private TabHost tabHost;
    /**
     * 百度地图使用类声明
     */
    private BaiDuMapUtil baiDuMapUtil;
    /**
     * 存储fragmentLsit
     */
    private List<Fragment> fragmentList;
    List<Map<String, String>> moreList;
    private PopupWindow pwMyPopWindow;// popupwindow
    private ListView lvPopupList;// popupwindow中的ListView
    private int NUM_OF_VISIBLE_LIST_ROWS = 3;// 指定popupwindow中Item的数量

    private View tabViewSameCity;
    private View tabViewRecommend;
    private View tabViewTopic;
    private View tabViewSelected;

    private SameCityFragment sameCityFragment;

    private TextView mainTabTabLine;
    private RelativeLayout headerLayout;

    public static View menuButton;

    private Button toggleMenuButton;
    private RelativeLayout slidingMenuItemOne;
    private RelativeLayout slidingMenuItemTwo;
    private RelativeLayout slidingMenuItemThree;
    private RelativeLayout slidingMenuItemFour;
    private ImageButton ibOperationMore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_tab);

        iniData();


        //开启百度云推送
        PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
                "2QmpGvP8HcEZw98gzWk2FnBQ");

        //初始化控件
        initView();
        //像ViewPager中添加Fragment
        putFragmentList();
        //设置ViewPager和TabHost的双向监听
        setTabPagerListener();
        //百度地图工具类实例化
        //baiDuMapUtil = new BaiDuMapUtil(MainTabActivity.this);



    }

    private void iniPopupWindow() {

        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.task_detail_popupwindow, null);
        lvPopupList = (ListView) layout.findViewById(R.id.lv_popup_list);
        pwMyPopWindow = new PopupWindow(layout);
        pwMyPopWindow.setFocusable(true);// 加上这个popupwindow中的ListView才可以接收点击事件

        lvPopupList.setAdapter(new SimpleAdapter(MainTabActivity.this, moreList,
                R.layout.list_item_popupwindow, new String[]{"share_key"},
                new int[]{R.id.tv_list_item}));
        lvPopupList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                FoodToast.makeText(MainTabActivity.this,
                        moreList.get(position).get("share_key"),
                        FoodToast.LENGTH_LONG).show();
            }
        });

        // 控制popupwindow的宽度和高度自适应
        lvPopupList.measure(View.MeasureSpec.UNSPECIFIED,
                View.MeasureSpec.UNSPECIFIED);
        pwMyPopWindow.setWidth(lvPopupList.getMeasuredWidth());
        pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight() + 10)
                * NUM_OF_VISIBLE_LIST_ROWS);

        // 控制popupwindow点击屏幕其他地方消失
        pwMyPopWindow.setBackgroundDrawable(this.getResources().getDrawable(
                R.mipmap.popwindow));// 设置背景图片，不能在布局中设置，要通过代码来设置
        pwMyPopWindow.setOutsideTouchable(true);// 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功，如上
    }

    private void iniData() {

        moreList = new ArrayList<Map<String, String>>();
        Map<String, String> map;
        map = new HashMap<String, String>();
        map.put("share_key", "北京");
        moreList.add(map);
        map = new HashMap<String, String>();
        map.put("share_key", "大连");
        moreList.add(map);
        map = new HashMap<String, String>();
        map.put("share_key", "上海");
        moreList.add(map);
    }

    /**控制侧滑栏的方法,内容详情,进入侧滑栏中查看*/
    public void toggleMenu(View view)
    {
        mLeftMenu.toggle();
    }
    public static void setToggleMenu(long ra) {
        menuButton.setRotation(ra);
    }

    /**
     * 初始化控件方法
     */
    private void initView() {
        mainTabViewPager = (ViewPager) findViewById(R.id.mainTabViewPager);
        tabHost = (TabHost) findViewById(android.R.id.tabhost);
        titleTextView = (TextView) findViewById(R.id.titleTextView);
        mainTabTabLine = (TextView) findViewById(R.id.mainTabTabLine);
        headerLayout = (RelativeLayout) findViewById(R.id.headerLayout);
        mLeftMenu = (SlidingMenu) findViewById(R.id.id_menu);

        toggleMenuButton = (Button) findViewById(R.id.toggleMenuButton);
        slidingMenuItemOne = (RelativeLayout) findViewById(R.id.slidingMenuItemOne);
        slidingMenuItemTwo = (RelativeLayout) findViewById(R.id.slidingMenuItemTwo);
        slidingMenuItemThree = (RelativeLayout) findViewById(R.id.slidingMenuItemThree);
        slidingMenuItemFour = (RelativeLayout) findViewById(R.id.slidingMenuItemFour);
        iniPopupWindow();
        titleTextView.setText(SAME_CITY_TITLE);
        //初始化TabHost
        initTabHostView();
        //设置主题
        setFoodTheme();
        menuButton = toggleMenuButton;

        MainTabMenuItemOnClickListener mainTabMenuItemOnClickListener = new MainTabMenuItemOnClickListener(MainTabActivity.this);
        //设置菜单的点击事件
        slidingMenuItemOne.setOnClickListener(mainTabMenuItemOnClickListener);
        slidingMenuItemTwo.setOnClickListener(mainTabMenuItemOnClickListener);
        slidingMenuItemThree.setOnClickListener(mainTabMenuItemOnClickListener);
        slidingMenuItemFour.setOnClickListener(mainTabMenuItemOnClickListener);

        // 更多操作按钮
        ibOperationMore = (ImageButton) findViewById(R.id.popWindow);
        ibOperationMore.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (pwMyPopWindow.isShowing()) {

                    pwMyPopWindow.dismiss();// 关闭
                } else {

                    pwMyPopWindow.showAsDropDown(ibOperationMore);// 显示
                }

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        //设置主题
        setFoodTheme();
    }

    /**
     * 初始化TabHost方法
     */
    private void initTabHostView() {
        //设置TabHost
        tabHost.setup();
        //构建同城Tab的View
        tabViewSameCity = getLayoutInflater().inflate(R.layout.tab_view_same_city, null);
        tabViewRecommend = getLayoutInflater().inflate(R.layout.tab_view_recommend,null);
        tabViewTopic = getLayoutInflater().inflate(R.layout.tab_view_topic, null);
        tabViewSelected = getLayoutInflater().inflate(R.layout.tab_view_selected, null);

        //添加同城TabView
        tabHost.addTab(tabHost.newTabSpec(SAME_CITY).setIndicator(tabViewSameCity).setContent(android.R.id.tabcontent));
        tabHost.addTab(tabHost.newTabSpec(RECOMMEND).setIndicator(tabViewRecommend).setContent(android.R.id.tabcontent));
        tabHost.addTab(tabHost.newTabSpec(TOPIC).setIndicator(tabViewTopic).setContent(android.R.id.tabcontent));
        tabHost.addTab(tabHost.newTabSpec(SELECTED).setIndicator(tabViewSelected).setContent(android.R.id.tabcontent));

    }

    /**
     * 向ViewPager中添加Fragment
     */
    private void putFragmentList() {
        //定义并初始化Fragment的List
        fragmentList = new ArrayList<Fragment>();
        //向Fragment的List加入Fragment
        sameCityFragment = new SameCityFragment();
        fragmentList.add(sameCityFragment);
        fragmentList.add(new RecommendFragment());
        fragmentList.add(new TopicsFragment());
        fragmentList.add(new SelectedFragment());
        //初始化ViewPager的Adapter
        adapter = new MainTabFragmentAdapter(getSupportFragmentManager(), fragmentList);
        mainTabViewPager.setAdapter(adapter);
    }

    /**
     * 设置TabHost和ViewPager的双向监听
     */
    private void setTabPagerListener() {
        //设置ViewPager的滑动事件监听
        mainTabViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            /**
             * 选中Pager后的回调方法
             * @param i 当前ViewPager的位置
             */
            @Override
            public void onPageSelected(int i) {
                SameCityFragment sameCityFragment = (SameCityFragment) fragmentList.get(0);
                switch (i) {
                    //当位置是同城位置时
                    case SAME_CITY_POSITION:
                        //设置TabHost的Tab为同城Tab
                        tabHost.setCurrentTabByTag(SAME_CITY);
                        sameCityFragment.setFloatingActionMenuVisible(View.VISIBLE);
                        titleTextView.setText(SAME_CITY_TITLE);
                        break;
                    case 1 :
                        tabHost.setCurrentTabByTag(RECOMMEND);
                        sameCityFragment.setFloatingActionMenuVisible(View.INVISIBLE);
                        titleTextView.setText(RECOMMEND_TITLE);
                        break;
                    case 2 :
                        tabHost.setCurrentTabByTag(TOPIC);
                        sameCityFragment.setFloatingActionMenuVisible(View.INVISIBLE);
                        titleTextView.setText(TOPIC_TITLE);
                        break;
                    case 3 :
                        tabHost.setCurrentTabByTag(SELECTED);
                        sameCityFragment.setFloatingActionMenuVisible(View.INVISIBLE);
                        titleTextView.setText(SELECTED_TITLE);
                        break;
                    default:
                        //错误位置Log打印
                        Log.i(LOG_TAG, "setTabPagerListener()#addOnPageChangeListener()#" +
                                "OnPageChangeListener()#onPageSelected() i is wrong");
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        //设置TabHost点击事件监听
        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            SameCityFragment sameCityFragment = (SameCityFragment) fragmentList.get(0);

            @Override
            public void onTabChanged(String tabId) {
                View view = tabHost.getCurrentTabView();
                Log.i(LOG_TAG, "tabId = " + tabId);
                //当tab的Tag为同城Tag时
                if (SAME_CITY.equals(tabId)) {
                    //设置ViewPager的页面为同城页
                    mainTabViewPager.setCurrentItem(0, false);
                    sameCityFragment.setFloatingActionMenuVisible(View.VISIBLE);
                } else if (RECOMMEND.equals(tabId)) {
                    mainTabViewPager.setCurrentItem(1, false);
                    sameCityFragment.setFloatingActionMenuVisible(View.INVISIBLE);
                } else if (TOPIC.equals(tabId)) {
                    mainTabViewPager.setCurrentItem(2, false);
                    sameCityFragment.setFloatingActionMenuVisible(View.INVISIBLE);
                } else if (SELECTED.equals(tabId)) {
                    mainTabViewPager.setCurrentItem(3, false);
                    sameCityFragment.setFloatingActionMenuVisible(View.INVISIBLE);
                } else {
                    //当tabId错误时打印Log
                    Log.i(LOG_TAG, "setTabPagerListener()#setOnTabChangedListener()#" +
                            "OnTabChangeListener()#onTabChanged tabId is wrong");
                }
                //设置抖动动画效果
                CommonUtil.setAnimation(MainTabActivity.this, view);
            }
        });
    }

    /**
     * 设置主题
     */
    public void setFoodTheme() {
        ImageView sameCityImageView = (ImageView) tabViewSameCity.findViewById(R.id.tabSameCityImageView);
        ImageView recommendImageView = (ImageView) tabViewRecommend.findViewById(R.id.tabRecommendImageView);
        ImageView topicImageView = (ImageView) tabViewTopic.findViewById(R.id.tabTopicImageView);
        ImageView selectedImageView = (ImageView) tabViewSelected.findViewById(R.id.tabSelectedImageView);
        sameCityImageView.setImageResource(FoodTheme.getTabSameCityImage());
        recommendImageView.setImageResource(FoodTheme.getTabRecommendImage());
        topicImageView.setImageResource(FoodTheme.getTabTopicImage());
        selectedImageView.setImageResource(FoodTheme.getTabSelectedImage());

        mainTabTabLine.setBackgroundResource(FoodTheme.getMainTabTabLineColor());
        headerLayout.setBackgroundResource(FoodTheme.getHeaderLayoutColor());
        mLeftMenu.setBackgroundResource(FoodTheme.getMainTabActivityLeftMenuColor());
        toggleMenuButton.setBackgroundResource(FoodTheme.getToggleMenuButton());
    }
}
